import {Injectable} from '@angular/core';
import {Camera, CameraResultType, CameraSource} from '@capacitor/camera';

export interface Photo {
    filepath: any;
    webviewPath: string;
    fileType: string;
}

@Injectable({
    providedIn: 'root'
})
export class PhotoService {
    public photos: Photo[] = [];

    constructor() {
    }

    dataURLtoFile(url, fileType) {
        const urlS = atob(url);
        let n = urlS.length;
        const u8arr = new Uint8Array(n);
        while (n--) {
            u8arr[n] = urlS.charCodeAt(n);
        }
        return new Blob([u8arr], {type: fileType});
    }

    public async addNewToGallery(init = '', callback = null) {
        if (init) {
            this.photos = [];
            return;
        }
        const capturedPhoto = await Camera.getPhoto({
            resultType: CameraResultType.Base64,
            source: CameraSource.Camera,
            quality: 100
        });
        const fileData = {
            filepath: this.dataURLtoFile(capturedPhoto.base64String, capturedPhoto.format),
            fileType: capturedPhoto.format,
            webviewPath: capturedPhoto.base64String
        };
        this.photos.unshift(fileData);
        if (callback) {
            callback(fileData);
        }
    }
}
